
'use strict';

const config = require("./conf/conf");

// 导入koa模块
const Koa = require('koa');
// 导入koa-router模块
const Router = require('koa-router');
const request = require('request');
const urllib = require('url');

const router = new Router();
// 创建koa的实例app
const app = new Koa();
router.all(/^\/https?\:\/\/.*/i, async (ctx) => {
    let url = ctx.URL.pathname.substr(1);
    let hostname = urllib.parse(url).hostname;
    if(!config.proxy_domain[hostname]){
        ctx.status = 404;
        ctx.body = "not found!"
    }
    else if(ctx.header["proxy-token"] != config.proxy_token){
        ctx.status = 403;
        ctx.body = "not found!"
    }
    else{        
        const res = await ctx.req.pipe(request(url,{ method: ctx.method})) // 这里请求真正的接口
        ctx.body = res
    }
  });

app.use(router.routes());

// 监听端口
app.listen(3000, () => {
    console.log("服务器已启动，http://localhost:3000");
})